﻿using Rainbow_Game_Fans.Common;
using Rainbow_Game_Fans.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Store;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.UI;



// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace Rainbow_Game_Fans
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class SettingPage : Page
    {
        private readonly NavigationHelper navigationHelper;
        private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();

        ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        double SavedSliderValue;
        public SettingPage()
        {
            this.InitializeComponent();
            

            // 仅支持方向为纵向的中心
            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;

            this.NavigationCacheMode = NavigationCacheMode.Required;

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
        }

        /// <summary>
        /// 获取与此 <see cref="Page"/> 关联的 <see cref="NavigationHelper"/>。
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// 获取此 <see cref="Page"/> 的视图模型。
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。  在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源; 通常为 <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 字典。 首次访问页面时，该状态将为 null。</param>
        private  void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {    
            // TODO:  创建适用于问题域的合适数据模型以替换示例数据
            //var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
            //this.DefaultViewModel["Groups"] = sampleDataGroups;
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="sender">事件的来源；通常为 <see cref="NavigationHelper"/></param>
        ///<param name="e">提供要使用可序列化状态填充的空字典
        ///的事件数据。</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            // TODO: 在此处保存页面的唯一状态。
        }
        #region NavigationHelper 注册

        /// <summary>
        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// <para>
        /// 应将页面特有的逻辑放入
        /// <see cref="NavigationHelper.LoadState"/>
        /// 和 <see cref="NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在早期会话期间保留的页面状态之外，
        /// LoadState 方法中还提供导航参数。
        /// </para>
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if( localSettings.Values["slider_brightness_Value"] != null )
                SavedSliderValue = (double)localSettings.Values["slider_brightness_Value"];

            tb_Version.Text = GetVersionString();
            string IsNightMode;
            if (localSettings.Values["NightMode"] != null)
            {
                IsNightMode = localSettings.Values["NightMode"].ToString();
                if (IsNightMode == "false")
                {
                    ts_NightMode.IsOn = false;
                    slider_brightness.IsEnabled = false;
                }
                else
                {
                    //if (ts_NightMode.IsOn == false )
                    ts_NightMode.IsOn = true;
                    slider_brightness.IsEnabled = true;
                }
            }
            if (localSettings.Values["slider_brightness_Value"] != null)
                slider_brightness.Value =(double) localSettings.Values["slider_brightness_Value"];
            
             this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            
        }

        #endregion
        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        /// 

        #region 关于页面

        string GetVersionString()
        {
            String appVersion = String.Format("{0}.{1}.{2}.{3}", Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build, Package.Current.Id.Version.Revision);
            return appVersion;
        }
        private async void hbtn_feedback_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri("mailto:a15108387617@live.com?subject=彩虹游戏迷 反馈");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async  void hbtn_CheckNewVersion_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri(string.Format("ms-windows-store:navigate?appid={0}", CurrentApp.AppId));
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async  void hbtn_rateme_Click(object sender, RoutedEventArgs e)
        {
            var uri = new Uri(String.Format("ms-windows-store:reviewapp?appid={0}", CurrentApp.AppId));
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        #endregion


        private async void hbtn_support_Click(object sender, RoutedEventArgs e)
        {
            //Buy();
            ContentDialog_Donate contentDialog_Donate = new ContentDialog_Donate(); //ContentDialog1是系统自带的内容对话框页面
            await contentDialog_Donate.ShowAsync();
        }

       // #region 付费支持

       // string BuyMessage;
       // string dialog_PrimaryButton_Text;
       // string producctID = "Rainbow_Game_Fans_Donate";
        
       // private async  void hbtn_support_Click(object sender, RoutedEventArgs e)
       // {
       //     //Buy();
       //     ContentDialog_Donate contentDialog1 = new ContentDialog_Donate(); //ContentDialog1是系统自带的内容对话框页面
       //     await contentDialog1.ShowAsync();
       // }
       // //耐久型物品购买
       ////async  void Buy()
       //// {
       ////     ////var uri = new Uri(String.Format("ms-windows-store:navigate?appid={0}", "c572d421-6efd-4c19-afb5-22f19095187e"));
       ////     ////await Windows.System.Launcher.LaunchUriAsync(uri);

       ////     LicenseInformation licenseInformation = CurrentApp.LicenseInformation;
       ////     if (!licenseInformation.ProductLicenses[producctID].IsActive)
       ////     {
       ////         //rootPage.NotifyUser("Buying Product 2...", NotifyType.StatusMessage);
       ////         try
       ////         {
       ////             await CurrentApp.RequestProductPurchaseAsync(producctID);
       ////             if (licenseInformation.ProductLicenses[producctID].IsActive)
       ////             {
       ////                 BuyMessage = "购买成功，谢谢支持";
       ////                 dialog_PrimaryButton_Text = "确定";

       ////             }
       ////             else
       ////             {
       ////                 BuyMessage = "购买失败，请重试";
       ////                 dialog_PrimaryButton_Text = "重试";
       ////             }
       ////         }
       ////         catch (Exception)
       ////         {
       ////             BuyMessage = "无法购买，请重试";
       ////             dialog_PrimaryButton_Text = "重试";
       ////         }
       ////     }
       ////     else
       ////     {
       ////         BuyMessage = "你已经购买过了，谢谢支持";
       ////         dialog_PrimaryButton_Text = "确定";
       ////     }
       ////     ShowDialog_Exit();
       //// }

       // async void Buy()//消耗型物品 购买
       // {
       //     //Log("Buying Product 1...", NotifyType.StatusMessage);
       //     try
       //     {
       //         PurchaseResults purchaseResults = await CurrentApp.RequestProductPurchaseAsync(producctID);
       //         switch (purchaseResults.Status)
       //         {
       //             case ProductPurchaseStatus.Succeeded:
       //                  BuyMessage = "购买成功，谢谢支持";
       //                  dialog_PrimaryButton_Text = "确定";

       //                 //GrantFeatureLocally(producctID, purchaseResults.TransactionId);
       //                  FulfillproducctID(producctID, purchaseResults.TransactionId);
       //                 break;
       //             case ProductPurchaseStatus.NotFulfilled:
       //             //    if (!IsLocallyFulfilled(producctID, purchaseResults.TransactionId))
       //             //    {
       //             //        GrantFeatureLocally(producctID, purchaseResults.TransactionId);
       //             //    }
       //                 BuyMessage = "购买失败，请重试";
       //                 dialog_PrimaryButton_Text = "重试";
       //                 FulfillproducctID(producctID, purchaseResults.TransactionId);
       //                 break;
       //             case ProductPurchaseStatus.NotPurchased:
       //                 //Log("Product 1 was not purchased.", NotifyType.StatusMessage);
       //                  BuyMessage = "购买失败，请重试";
       //                  dialog_PrimaryButton_Text = "重试";
       //                 break;
       //         }
       //     }
       //     catch (Exception)
       //     {
       //         //Log("Unable to buy Product 1.", NotifyType.ErrorMessage);
       //         BuyMessage = "无法购买，请重试";
       //         dialog_PrimaryButton_Text = "重试";
       //     }
       //     ShowDialog_Exit();
       // }
        
       // private async void FulfillproducctID(string productId, Guid transactionId)  //消耗掉物品，以便再次购买
       // {
       //     try
       //     {
       //         FulfillmentResult result = await CurrentApp.ReportConsumableFulfillmentAsync(productId, transactionId);
       //         //switch (result)
       //         //{
       //         //    case FulfillmentResult.Succeeded:
       //         //        //Log("You bought and fulfilled product 1.", NotifyType.StatusMessage);
                        
       //         //        break;
       //         //    case FulfillmentResult.NothingToFulfill:
       //         //        Log("There is no purchased product 1 to fulfill.", NotifyType.StatusMessage);
       //         //        break;
       //         //    case FulfillmentResult.PurchasePending:
       //         //        Log("You bought product 1. The purchase is pending so we cannot fulfill the product.", NotifyType.StatusMessage);
       //         //        break;
       //         //    case FulfillmentResult.PurchaseReverted:
       //         //        Log("You bought product 1. But your purchase has been reverted.", NotifyType.StatusMessage);
       //         //        // Since the user's purchase was revoked, they got their money back.
       //         //        // You may want to revoke the user's access to the consumable content that was granted.
       //         //        break;
       //         //    case FulfillmentResult.ServerError:
       //         //        Log("You bought product 1. There was an error when fulfilling.", NotifyType.StatusMessage);
       //         //        break;
       //         //}
       //     }
       //     catch (Exception)
       //     {
       //         //Log("You bought Product 1. There was an error when fulfilling.", NotifyType.ErrorMessage);
       //     }
       //     //ShowDialog_Exit();
       // }

       // //private void Log(string message, NotifyType type)
       // //{
       // //    string logMessage = message + "\n\n" + GetFulfillmentResults();
       // //    rootPage.NotifyUser(logMessage, type);
       // //}

       // //private int numberOfConsumablesPurchased = 0;
       // //private Dictionary<string, List<Guid>> grantedConsumableTransactionIds = new Dictionary<string, List<Guid>>();

       // //private string GetFulfillmentResults()
       // //{
       // //    string message = "Product 1 has been fulfilled " + numberOfConsumablesPurchased + " time" + (numberOfConsumablesPurchased == 1 ? "" : "s") + ".";
       // //    return message;
       // //}

       // //private void GrantFeatureLocally(string productId, Guid transactionId)
       // //{
       // //    if (!grantedConsumableTransactionIds.ContainsKey(productId))
       // //    {
       // //        grantedConsumableTransactionIds.Add(productId, new List<Guid>());
       // //    }
       // //    grantedConsumableTransactionIds[productId].Add(transactionId);

       // //    // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
       // //    numberOfConsumablesPurchased++;
       // //}

       // //private Boolean IsLocallyFulfilled(string productId, Guid transactionId)
       // //{
       // //    return grantedConsumableTransactionIds.ContainsKey(productId) && grantedConsumableTransactionIds[productId].Contains(transactionId);
       // //}

       // async void ShowDialog_Exit()
       // {
            
       //     ContentDialog dialog = new ContentDialog()
       //     {
       //         Title = "购买确认", //标题
       //         Content = BuyMessage,//内容
       //         FullSizeDesired = false,  //是否全屏展示
       //         PrimaryButtonText = dialog_PrimaryButton_Text,//第一个按钮内容
       //         SecondaryButtonText = "取消"
       //     };
       //     dialog.Background = new SolidColorBrush(Colors.Red);
       //     if (localSettings.Values["slider_brightness_Value"] != null)
       //     {
       //         dialog.Opacity = (double)localSettings.Values["slider_brightness_Value"];
       //     }
       //     dialog.SecondaryButtonClick += dialog_SecondaryButtonClick;//第二个按钮单击事件
       //     dialog.PrimaryButtonClick += dialog_PrimaryButtonClick;

       //     ContentDialogResult result = await dialog.ShowAsync();
       //     if (result == ContentDialogResult.Primary) { } //处理第一个按钮的返回
       //     else if (result == ContentDialogResult.Secondary) { }//处理第二个按钮的返回

       // }
       // void dialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
       // {
       //     //await new MessageDialog("您选择了第一个按钮").ShowAsync();
       //     if (dialog_PrimaryButton_Text == "重试")
       //         Buy();
       //     //else 
       //     //    this.navigationHelper.GoBack();
       // }
       // void dialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
       // {
       //     //await new MessageDialog("您选择了第二个按钮").ShowAsync();
       // }
       // #endregion

        #region 夜间模式
        private void slider_brightness_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if (slider_brightness !=null )
            {
                int  slider_value;
                slider_value =(int)(slider_brightness.Value * 100);
                tb_BrightnessValue.Text = slider_value.ToString();
                localSettings.Values["slider_brightness_Value"] = slider_brightness.Value;
            }
        }       
        private void ts_NightMode_Toggled(object sender, RoutedEventArgs e)
        {
            if (ts_NightMode.IsOn == false)
            {
                SavedSliderValue = slider_brightness.Value;

                slider_brightness.Value = 1;
                slider_brightness.IsEnabled = false;
                //SetNightModeOFF();
                localSettings.Values["NightMode"] = "false";
            }
            else
            {
                slider_brightness.Value = SavedSliderValue;
                slider_brightness.IsEnabled = true;
                //SetNightModeON();
                localSettings.Values["NightMode"] = "true";
            }
        }

        #endregion


    }
}
